package cc.mango.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class URLHelper
{

	//private static final String		CONTENT_TYPE_ATTR		= "Content-type";
	//private static final String		CONTENT_TYPE_VALUE		= "application/x-www-form-urlencoded";
	//	private static final String		CHARSET_ATTR					=	"Accept-Charset";
	//	private static final String		CHARSET_VALUE					=	"UTF-8";
	//private static final String		CONTENT_LENGTH_ATTR		= "Content-length";
	//private static final String		COOKIE_ATTR						=	"Cookie";
	//private static final String		SET_COOKIE_ATTR			=	"Set-Cookie";

	private static final String	HTTP_OUTPUT_ENCODING	= "UTF-8";

	//private static Logger			sysLog					=	Logger.getLogger(URLHelper.class);

	public static String post(String dest, int timeout)
	{
		//		sysLog.debug("URL: "+dest+",Param: "+param);
		// variables for store asiapay return parameter
		String result = null;
		try
		{

			// variables for store asiapay url
			URL url = new URL(dest);
			URLConnection urlCon = url.openConnection();

			//Call to keep connection alive as much as the data is done, Andy
			urlCon.addRequestProperty("Connection","Keep-Alive");
			urlCon.setConnectTimeout(timeout);

			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			
			//Explicit call connect, Andy
			urlCon.connect();

			// If I had old cookie, set here
			//String oldCookie=Cookies.getInstance().get(dest);
			//if(oldCookie!=null)	urlCon.setRequestProperty(COOKIE_ATTR, oldCookie);//oldCookie);
			// Set request headers for content type and length
			//urlCon.setRequestProperty(CONTENT_TYPE_ATTR, CONTENT_TYPE_VALUE);
			//			urlCon.setRequestProperty(CHARSET_ATTR, CHARSET_VALUE);

			//urlCon.setRequestProperty(CONTENT_LENGTH_ATTR, String.valueOf(param.length()));

			//Issue the POST request
			OutputStream outStream = urlCon.getOutputStream();
			//outStream.write(param.getBytes());
			outStream.flush();

			// If server return new cookie to me. set here
			//String newCookie=getCookie(urlCon);
			//if(newCookie!=null) Cookies.getInstance().add(dest, newCookie);

			//Read the response
			//			InputStream inStream = urlCon.getInputStream();

			StringBuffer tmpsb = new StringBuffer();
			//			while (true) {
			//				int c = inStream.read();
			//				if (c == -1)
			//					break;
			//				tmpsb.append((char)c);
			//			}

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(urlCon.getInputStream(),
							HTTP_OUTPUT_ENCODING));
			String line;
			while ((line = reader.readLine()) != null)
				tmpsb.append(line);

			// the return string contains <CR>, need to ge rid of that.
			result = tmpsb.toString().trim();

			//			sysLog.debug("post(): i have the result\"" + result + "\"");

			//			inStream.close();
			reader.close();
			outStream.close();			
		}
		catch (Exception e)
		{
			//sysLog.error("cannot post: "+e.getMessage());

			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			//sysLog.error("cannot post:"+ sw.toString());
		}

		return result;

	}

	public static ArrayList<String> getAsList(String dest, int timeout)
			throws SocketTimeoutException
	{
		ArrayList<String> result = new ArrayList<String>();

		try
		{

			// variables for store asiapay url
			URL url = new URL(dest);
			URLConnection urlCon = url.openConnection();
			
			urlCon.setConnectTimeout(timeout);
			//Call to keep connection alive as much as the data is done, Andy
			urlCon.addRequestProperty("Connection","Keep-Alive");
			
			//by zhengan,设置读数据超时
			urlCon.setReadTimeout(timeout * 4);

			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);

			//Explicit call connect, Andy
			urlCon.connect();
			
			//Issue the POST request
			//OutputStream outStream = urlCon.getOutputStream();
			//outStream.write(param.getBytes());
			//outStream.flush();

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(urlCon.getInputStream(),
							HTTP_OUTPUT_ENCODING));
			String line;
			while ((line = reader.readLine()) != null)
				result.add(line);

			reader.close();
			//outStream.close();

		}
		catch (SocketTimeoutException e)
		{

			e.printStackTrace();

			throw new SocketTimeoutException();
		}
		catch (IOException e)
		{
			//sysLog.error("cannot post: "+e.getMessage());

			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			//sysLog.error("cannot post:"+ sw.toString());
		}

		return result;

	}

	public static ArrayList<String> getAsList2(String dest, int timeout)
	{
		ArrayList<String> result = new ArrayList<String>();
		String httpResponse = "";

		final DefaultHttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
		HttpConnectionParams.setSoTimeout(httpParams, timeout);
		client.setParams(httpParams);
		HttpGet httpMethod = new HttpGet(dest);
		
		//Call to keep connection alive as much as the data is done, Andy
		httpMethod.addHeader("Connection", "Keep-Alive");
		try
		{
			client.execute(httpMethod, new ResponseHandler<String>()
			{
				public String handleResponse(HttpResponse response)
				{
					// when the response happens close the notification and update UI

					HttpEntity entity = response.getEntity();
					String httpResponse = null;

					try
					{
						httpResponse = StringUtils
								.inputStreamToString(entity
										.getContent());
					}
					catch (IOException e1)
					{
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					return httpResponse;
				}
			});
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		String[] array = httpResponse.split("[\\r\\n]");
		for (int index = 1, length = array.length; index < length; index++)
		{
			String currentLine = array[index].trim();
			if (currentLine.length() > 0)
			{
				result.add(currentLine);
			}
		}
		/*
		
		try {
			Log.e(ChartPanel.TAG,"URLHelper.getAsList() -> " + dest);
			// variables for store asiapay url
			URL url = new URL (dest);
			URLConnection urlCon = url.openConnection();
			urlCon.setConnectTimeout(timeout);

			urlCon.setDoOutput(true);
			urlCon.setDoInput(true);
			
			OutputStream outStream = urlCon.getOutputStream();
			//outStream.write(param.getBytes());
			outStream.flush();
			
			//Read the response
			BufferedReader reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), HTTP_OUTPUT_ENCODING));
			String line;
			while ((line = reader.readLine()) != null)
				result.add(line);
			
			reader.close();
			outStream.close();

		} catch (Exception e) {
			//sysLog.error("cannot post: "+e.getMessage());
			
		    StringWriter sw = new StringWriter();
		    PrintWriter pw = new PrintWriter(sw);
		    e.printStackTrace(pw);
		}
		*/
		return result;

	}

}